package com.study.lease.web.app.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.study.lease.model.entity.BrowsingHistory;
import com.study.lease.web.app.mapper.BrowsingHistoryMapper;
import com.study.lease.web.app.service.BrowsingHistoryService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.study.lease.web.app.vo.history.HistoryItemVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import java.util.Date;

/**
 * @author liubo
 * @description 针对表【browsing_history(浏览历史)】的数据库操作Service实现
 * @createDate 2023-07-26 11:12:39
 */
@Service
public class BrowsingHistoryServiceImpl extends ServiceImpl<BrowsingHistoryMapper, BrowsingHistory>
        implements BrowsingHistoryService {
    @Autowired
    private BrowsingHistoryMapper browsingHistoryMapper;


    /**
     * 分页查询浏览记录
     * @param page
     * @param userId
     * @return
     */
    @Override
    public IPage<HistoryItemVo> pageHistoryItemByUserId(Page<HistoryItemVo> page, Long userId) {
        return browsingHistoryMapper.pageHistoryItemByUserId(page, userId);
    }

    /**
     * 保存浏览记录
     * @param userId
     * @param id
     */
    @Override
    @Async //异步执行
    public void saveHistory(Long userId, Long id) {
        /**
         * 一个用户只会有一个浏览记录，一个用户多次浏览只更新浏览时间即可
         */
        LambdaQueryWrapper<BrowsingHistory> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(BrowsingHistory::getUserId, userId);
        queryWrapper.eq(BrowsingHistory::getRoomId, id);
        BrowsingHistory browsingHistory = browsingHistoryMapper.selectOne(queryWrapper);

        // 如果存在，则更新浏览时间
        if (browsingHistory != null){
            browsingHistory.setBrowseTime(new Date());
        }else {
            // 如果不存在，则新建浏览记录
            BrowsingHistory browsingHistory1 = new BrowsingHistory();
            browsingHistory1.setUserId(userId);
            browsingHistory1.setRoomId(id);
            browsingHistory1.setBrowseTime(new Date());
            browsingHistoryMapper.insert(browsingHistory1);
        }
    }
}